<?php

namespace App\Http\Controllers\Fee;

use App\Http\Controllers\BaseController;
use App\Models\Fee\FeeType;
use App\Services\Chanjet\ChanjetRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * 费用类型相关
 */
class FeeTypeController extends BaseController
{
    public static $feeTypeCategory = ["1"=>"销售费用","2"=>"采购费用","3"=>"其他费用"];
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        //需获取当前用户所属账套
        $status = $request->status ?? 0;
        $isgetall = $request->isgetall ?? 0;

        $list = FeeType::getList($request, $this->mangerinfo['cpid'], $status, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 新增
     */
    public function dopostadd(Request $request)
    {
        $type_name = $request->type_name ?? '';
        $category = intval($request->category) ?? 1;

        if (!in_array($category, [1, 2, 3])) {
            return response()->json(['code' => '001', 'msg' => '类型参数错误']);
        }

        if ($type_name == '') {
            return response()->json(['code' => '001', 'msg' => '费用类型名称不允许为空']);
        }
        // $isexist = FeeType::where([['category', $category],['type_name', $type_name],['cpid' , $this->mangerinfo['cpid']]])->first();
        $isexist = FeeType::where([['category', $category], ['type_name', $type_name], ['is_del', 1]])->whereIn('cpid', [0, $this->mangerinfo['cpid']])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '费用类型名称不允许重复']);
        }
        $data = [
            'cpid' => $this->mangerinfo['cpid'],
            'category' => $category,
            'type_name' => $type_name,
            'update_at' => time(),
            'create_at' => time()
        ];
        $createId = FeeType::create($data)->id;

        $this->syncFeetype(['createId'=>$createId,'type_name'=>$type_name,'category'=>$category],'add');

        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $id = $request->id ?? 0;

        $category = $request->category ?? 1;

        if (!in_array($category, [1, 2, 3])) {
            return response()->json(['code' => '001', 'msg' => '类型参数错误']);
        }

        $info = FeeType::where([['id', $id], ['cpid', $this->mangerinfo['cpid']], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }



        $type_name = $request->type_name ?? '';

        if ($type_name == '') {
            return response()->json(['code' => '001', 'msg' => '费用类型名称不允许为空']);
        }
        $isexist = FeeType::where([['id', '<>', $id], ['type_name', $type_name], ['is_del', 1]])->whereIn('cpid', [0, $this->mangerinfo['cpid']])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '费用类型名称不允许重复']);
        }

        $data = [
            'type_name' => $type_name,
            'category' => $category,
            'update_at' => time()
        ];
        FeeType::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->update($data);

        $this->syncFeetype(['createId'=>$id,'type_name'=>$type_name,'category'=>$category],'edit');

        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 冻结
     */
    public function changestatus(Request $request)
    {

        $id = $request->id ?? 0;
        $info = FeeType::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $status = 2;
        FeeType::where([['id', $id]])->update(['status' => $status, 'update_at' => time()]);

        $this->syncFeetype(['createId'=>$id],'freeze');

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    /**
     * 删除
     */
    public function dodel(Request $request)
    {

        $id = $request->id ?? 0;
        $info = FeeType::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        FeeType::where([['id', $id]])->update(['is_del' => 2, 'del_at' => time()]);

        $this->syncFeetype(['createId'=>$id],'delete');

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
    /**
     *  费用类型分类
    */
    public function getFeeTypeCategory(){
        $data = [];
        foreach (self::$feeTypeCategory as $key=>$item){
            $data[] = [
                'category' => $key,
                'type_name' => $item
            ];
        }
        return response()->json(['code'=>"000","data"=>["list"=>$data]]);
    }
    /***
     *  t+同步费用类型
     *
    */
    public function syncFeetype($data = [],$operate = 'add'){
        $start_block = microtime(true);

        if(!$this->mangerinfo['org_id']){
            return false;
        }
        if(isset($data['category'])){
            if($data['category'] == '1') $data["ExpenseTypeName"] = "销售费用";
            if($data['category'] == '2') $data["ExpenseTypeName"] = "采购费用";
            if($data['category'] == '3') $data["ExpenseTypeName"] = "其他费用";
        }
        $Chanjet_param = [
            "dto" => [
                "Code" => 'fee_type_'.$data["createId"],
            ]
        ];
        if($operate == "add"){
            //获取费用分类code
            $Chanjet_param["dto"]["Name"] = $data["type_name"];
            $Chanjet_param["dto"]["ExpenseType"]["Name"] = $data["ExpenseTypeName"];

            //$Code = $this->getFeeTypeCateCode($data);
            //$Chanjet_param["dto"]["Parent"]["Code"] = $Code;
            $requestData = [
                "api" => "ExpenseCreate",
                "param" => $Chanjet_param,
                "mangerinfo" => $this->mangerinfo
            ];
            \App\Jobs\Manger::dispatch($requestData);
        }
        if($operate == "edit"){
            $Chanjet_param["dto"]["Name"] = $data["type_name"];
            $Chanjet_param["dto"]["ExpenseType"]["Name"] = $data["ExpenseTypeName"];

            $requestData = [
                "api" => "ExpenseUpdate",
                "param" => $Chanjet_param,
                "mangerinfo" => $this->mangerinfo
            ];
            \App\Jobs\Manger::dispatch($requestData);
        }
        if($operate == "freeze"){
            $Chanjet_param["dto"]["Disabled"] = "true";
            $requestData = [
                "api" => "ExpenseUpdate",
                "param" => $Chanjet_param,
                "mangerinfo" => $this->mangerinfo
            ];
            \App\Jobs\Manger::dispatch($requestData);
        }
        if($operate == "delete"){
            $requestData = [
                "api" => "ExpenseDelete",
                "param" => $Chanjet_param,
                "mangerinfo" => $this->mangerinfo
            ];
            \App\Jobs\Manger::dispatch($requestData);
        }

        $time_block = microtime(true)- $start_block;
        Log::info("同步费用,time: ".$time_block);
    }
    /**
     *   根据分类名称获取 分类code
     *
    */
    public function getFeeTypeCateCode($data = []){
        if($data["category"] == "1"){
            $code = "sale";
            $type_name = "销售费用";
        }
        if($data["category"] == "2"){
            $code = "purchase";
            $type_name = "采购费用";
        }
        if($data["category"] == "3"){
            $code = "other";
            $type_name = "其他费用";
        }
        //getFeeTypeCateCode
        $chanjet_param = [
            "dto" => [
                "Code"=>$code,
                "Name"=>$type_name,
                "ExpenseType"=>[
                    "Name" => $type_name
                ]
            ]
        ];
        $res = ChanjetRequest::getInstance()->ExpenseQuery($chanjet_param,$this->mangerinfo['org_id']);
        if(empty($res)){
            //新增分类
            ChanjetRequest::getInstance()->ExpenseCreate($chanjet_param,$this->mangerinfo['org_id']);
        }
        return $code;
    }
}
